package com.ja.openchat.ui.me;

import android.graphics.Color;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.lifecycle.Observer;

import com.blankj.utilcode.util.BarUtils;
import com.blankj.utilcode.util.SizeUtils;
import com.google.android.material.appbar.AppBarLayout;
import com.google.gson.JsonObject;
import com.ja.openchat.BR;
import com.ja.openchat.R;
import com.ja.openchat.databinding.FragmentMyAlbumBinding;
import com.ja.openchat.ui.found.CircleMessageActivity;
import com.ja.openchat.viewmodels.MyAlbumViewModel;
import com.ja.openchat.views.QBadgeView;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.interfaces.OnConfirmListener;
import com.scwang.smart.refresh.layout.api.RefreshHeader;
import com.scwang.smart.refresh.layout.simple.SimpleMultiListener;
import com.yanzhenjie.recyclerview.widget.DefaultItemDecoration;
import com.zy.openchat.core.manager.TelegramManager;
import com.zy.openchat.core.manager.TgResultBlock;
import com.zy.openchat.core.model.user.UserMyInfo;
import com.zy.openchat.util.Common;

import java.util.Map;

import me.goldze.mvvmhabit.base.BaseFragment;
import me.goldze.mvvmhabit.utils.KLog;
import me.goldze.mvvmhabit.utils.StatusBarUtil;
import q.rorbin.badgeview.Badge;

//我的相册
public class MyAlbumFragment extends BaseFragment<FragmentMyAlbumBinding, MyAlbumViewModel> {
    private int mOffset = 0;
    private int mScrollY = 0;
    private boolean isDragLoadMore = false;

    @Override
    public int initContentView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return R.layout.fragment_my_album;
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }

    @Override
    public void initView() {
        super.initView();
        //状态栏透明和间距处理
        BarUtils.setStatusBarColor(getActivity(), Color.TRANSPARENT);
        BarUtils.subtractMarginTopEqualStatusBarHeight(getActivity().findViewById(R.id.content));
        StatusBarUtil.setPaddingSmart(getActivity(), binding.topToolbar);
        StatusBarUtil.setMargin(getActivity(), binding.header);
        binding.refreshLayout.setOnMultiListener(new SimpleMultiListener() {
            @Override
            public void onHeaderMoving(RefreshHeader header, boolean isDragging, float percent, int offset, int headerHeight, int maxDragHeight) {
                super.onHeaderMoving(header, isDragging, percent, offset, headerHeight, maxDragHeight);
                if (isDragLoadMore)
                    return;
                mOffset = offset / 2;
                binding.parallax.setTranslationY(mOffset - mScrollY);
                binding.topToolbar.setAlpha(1 - Math.min(percent, 1));
            }

        });
        binding.topToolbar.setBackgroundColor(0);
        binding.topToolbar.setTitleAlpha(0);
        BarUtils.setStatusBarLightMode(getActivity(), false);
        binding.recyclerView.addItemDecoration(new DefaultItemDecoration(getResources().getColor(R.color.white), SizeUtils.dp2px(9), SizeUtils.dp2px(9)));
        binding.appBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
            private int color = ContextCompat.getColor(getContext(), R.color.white) & 0x00ffffff;

            @Override
            public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
                if (verticalOffset != 0)
                    binding.parallax.setTranslationY(verticalOffset / 2);
                float textAlpha = (float) (appBarLayout.getTotalScrollRange() / 2.0);
                if (Math.abs(verticalOffset) > textAlpha) {
                    isDragLoadMore = true;
//                    binding.topToolbar.setTitle("我的相册");
                    textAlpha = (Math.abs(verticalOffset) - textAlpha) / textAlpha;
                    if (textAlpha > 1)
                        textAlpha = 1;
                    binding.topToolbar.setTitleAlpha(textAlpha);
                    binding.topToolbar.setBackgroundColor(((int) (255 * textAlpha) << 24) | color);
                    if (Math.abs(verticalOffset) >= appBarLayout.getTotalScrollRange()) {
                        binding.topToolbar.setTitleAlpha(1);
                    }

                    BarUtils.setStatusBarLightMode(getActivity(), true);
                } else {

                    BarUtils.setStatusBarLightMode(getActivity(), false);
                    binding.topToolbar.setBackgroundColor(Color.TRANSPARENT);
                    isDragLoadMore = false;
//                    binding.topToolbar.setTitle("");
                }
            }
        });
        binding.topToolbar.setOnIconRightListener(v -> {
            startActivity(CircleMessageActivity.class);
        });
    }

    @Override
    public void initViewObservable() {
        super.initViewObservable();
        //监听上拉加载完成
        viewModel.uc.finishLoadmore.observe(this, o -> {
            //结束刷新
            binding.refreshLayout.finishLoadMore();
        });
        //监听下拉刷新完成
        viewModel.uc.finishRefreshing.observe(this, o -> {
            //结束刷新
            binding.refreshLayout.finishRefresh();
        });
        //监听是否启用加载更多
        viewModel.uc.enableFinishLoadmore.observe(this, aBoolean -> {
            KLog.d("enableFinishLoadmore==" + aBoolean);
            binding.refreshLayout.setEnableLoadMore(aBoolean);
        });
        viewModel.showDialogSingleLiveEvent.observe(this, new Observer<String>() {
            @Override
            public void onChanged(String s) {
                String title = getString(R.string.dialog_title_tip);
                new XPopup.Builder(getActivity()).autoDismiss(true).asConfirm(title, s, getString(R.string.cancle_text), getString(R.string.ok_text), new OnConfirmListener() {
                    @Override
                    public void onConfirm() {
                    }
                }, () -> {
                }, false).show();
            }
        });
        QBadgeView qBadgeView = new QBadgeView(getContext());
        qBadgeView.setBadgeTextSize(9, true);
        qBadgeView.setGravityOffset(10, 22, true);
        qBadgeView.bindTarget(binding.topToolbar).setBadgePadding(6,true)
                .setShowShadow(false)
                .setBadgeGravity(Gravity.TOP | Gravity.END)
                .setOnDragStateChangedListener(new Badge.OnDragStateChangedListener() {
                    @Override
                    public void onDragStateChanged(int dragState, Badge badge, View targetView) {
                    }
                });
        viewModel.msgSingleLiveEvent.observe(this, new Observer<Integer>() {
            @Override
            public void onChanged(Integer integer) {
                KLog.d("消息：" + integer);
                qBadgeView.setBadgeNumber(integer);
//                qBadgeView.setBadgeNumber(5);
            }
        });

    }

    private void loadUserInfoEx(){
        TelegramManager.getTelegramManager().getUserInfoEx(getContext(), viewModel.mUserId,new TgResultBlock<UserMyInfo>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, UserMyInfo obj) {
                if(obj!=null){
                    binding.sexTagIv.setImageResource(obj.gender == 0?R.mipmap.nearby_man:R.mipmap.nearby_women);
                    binding.userAgeStr.setText(String.format(getString(R.string.age_year_old), Common.getAgeByBirth(obj.birth)));
                    binding.userAddressStr.setText(obj.getAddress());
                }
            }

            @Override
            public void onTimeout(Map<String, Object> request) {

            }
        });
    }

    @Override
    public void initData() {
        super.initData();
        Bundle arguments = getArguments();
        viewModel.setData(arguments);
        loadUserInfoEx();
//        binding.refreshLayout.autoRefresh();
    }
}